package member.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import member.domain.Member;
import member.service.MemberService;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1. 요청 파라미터 조회
		String id = request.getParameter("id");
		String password = request.getParameter("password");
		//2. 비지니스 로직
		MemberService service = MemberService.getInstance();
		Member member = service.searchMemberById(id);
		//찾았으면 : 객체, 못찾으면 : null
		String url = null;
		if(member !=null){//id 존재
			if(password.equals(member.getPassword())){//로그인 성공
				url = "/member/login_success.jsp";
				//HttpSession 객체를 생성
				HttpSession session = request.getSession();
				//로그인 여부를 확인할 때 사용할 Attribute를 session에 binding
				session.setAttribute("login_member", member);
				
				
				
			}else{//ID : OK, Pwd 틀린 경우
				url = "/member/login_form.jsp";
				request.setAttribute("error_message", "패스워드를 확인하세요.");
			}
		}else{//id가 틀린 경우
			url = "/member/login_form.jsp";
			request.setAttribute("error_message", "ID를 확인하세요.");
		}
		RequestDispatcher rdp = request.getRequestDispatcher(url);
		rdp.forward(request, response);
	}
}

